import logging


from  google.appengine.api import urlfetch
from urlparse import urlparse

from django.utils import simplejson as json

from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from home.forms import LoginForm
from player.models import Player
def home(request):
    
    form = LoginForm(request.POST or None)
    if request.session.get('current_player'):
        return HttpResponseRedirect(reverse('player_home'))

    if form.is_valid():
        player = Player.is_valid(request.POST.get('password'),request.POST.get('email'))
        if player:
            request.session['current_player'] = player
            request.session.save()
            return HttpResponseRedirect(reverse('player_home'))
        
    return render_to_response('home.html',{'form':form})


def facebook_redirect(request):
    code = request.GET.get('code')
    
    if code:
        url ="https://graph.facebook.com/oauth/access_token?client_id=115052891913924&redirect_uri=http://quienesjuegan.appspot.com/facebook_cb/&client_secret=1c4f4060ab578777e3ece72c7658813f&code=%s"%code
        result = urlfetch.fetch(url).content
        r = result.split('&')[0]
        request.session['token'] = r.split('=')[1]
        request.session.save()        
        return HttpResponseRedirect(reverse('facebook_cb'))
    else:
        url = "https://graph.facebook.com/me/?access_token=%s"%request.session['token']
        result = urlfetch.fetch(url).content
        user_dict = json.loads(result)
        player = Player.create_player(user_dict.get('email'),user_dict.get('first_name'),user_dict.get('id'))
        request.session['current_player'] = player
        request.session.save()
        return HttpResponseRedirect(reverse('player_home'))
        
                
    return HttpResponse("ok")


